<?php

// +----------------------------------------------------------------------
// | Apprh.Shop
// +----------------------------------------------------------------------
// | Copyright (c) 2017-2027 http://www.apprh.com All rights reserved.
// +----------------------------------------------------------------------
// | Notice: This code is not open source, it is strictly prohibited
// |         to distribute the copy, otherwise it will pursue its
// |         legal responsibility.
// +----------------------------------------------------------------------
// | Author: 雲溪荏苒 <290648237@qq.com>
// +----------------------------------------------------------------------

namespace app\api\controller;

use axios\tpr\core\Api;


/**
 * 工具类
 * Class Tools
 * @package app\api\controller
 * @author andy <290648237@qq.com>
 * @date 2017/05/27
 */
class Tools extends Api
{

    public function api_search_city()
    {
        $cityList = D('area')->getOpenAreaByPid(I('get.provid', 25));
        $this->response($cityList);
    }

    public function api_search_dist()
    {
        $provid = I('get.provid');
        $cityId = I('get.cityid');

        $cityList = D('area')->getOpenAreaByPid($cityId);
        $this->response($cityList);
    }

    
    /**
     * andy-图片上传
     * @desc 支持多图上传
     * @parameter string save_path 图片保存文件夹（可选默认为“picture”）
     * @parameter string image base64字符串[如果是base64字符串上传，则需要传递image参数，多图为image数组；如果是file文件流上传，不需要传image参数，input#name="image[]"#type="file"]
     * @method post
     * @response
     */
    public function uploadFile()
    {


        $savePath = !empty($this->request->param('save_path')) ? $this->request->param('save_path') : 'picture';
        $setting = [
            'driver' => sysconf('storage_type'),
            'root_path' => './static/upload/'.$savePath.'/' // 图片保存路径 默认为'./static/upload/picture/'
        ];
        $uploadData = $this->uploadAndSaveData($setting);

        $resData = [
            'error' => 0,
            'code' => 0,
            'count' => 1,
            'message' => '上传成功',
            'url' => $uploadData['path'],
            'data' => [
//                'url' => $uploadData['path'],
                'add_time' => time(),
//                'dirname' => "",
                'extension' => "png",
                'file_name' => '1515',
                'height' => 55,
//                'host' => 'http://68yun.oss-cn-beijing.aliyuncs.com/images/11880/',
//                'name' => '/backend/1/images/2017/10/01/15068187669500.png',
                'size' => 53,
                'sort' => 255,
                'width' => 34,
                'path' =>  $uploadData['short_path'],
                'url' =>  $uploadData['path']
            ]
        ];
        echo json_encode($resData);
        exit();
//        $this->response($resData, 200, '上传成功');
    }

    public function uploadDoctorImage()
    {


        $savePath = !empty($this->request->param('save_path')) ? $this->request->param('save_path') : 'picture';
        $setting = [
            'driver' => sysconf('storage_type'),
            'root_path' => './static/upload/'.$savePath.'/' // 图片保存路径 默认为'./static/upload/picture/'
        ];
        $uploadData = $this->uploadAndSaveData($setting);
        $data = [
            'add_time' => time(),
//                'dirname' => "",
            'extension' => "jpg",
            'file_name' => '1515',
            'height' => 55,
            'host' => '',
            'name' => '',
            'size' => 53,
            'sort' => 255,
            'width' => 34,
            'path' =>  $uploadData['short_path'],
            'url' =>  $uploadData['path']
        ];
        $resData = [
            'code' => 0,
            'count' => 1,
            'message' => '上传成功',
            'data' => $data
        ];
        echo json_encode($resData);
        exit();
//        $this->response($resData, 200, '上传成功');
    }

    /**
     * xxx
     */
//    public function uploadDoctorDescImage()
//    {
//
//
//        $savePath = !empty($this->request->param('save_path')) ? $this->request->param('save_path') : 'picture';
//        $setting = [
//            'driver' => sysconf('storage_type'),
//            'root_path' => './static/upload/'.$savePath.'/' // 图片保存路径 默认为'./static/upload/picture/'
//        ];
//        $uploadData = $this->uploadAndSaveData($setting);
//        $data = [];
//        foreach ($uploadData as $item) {
//            $data[] = [
//                'add_time' => time(),
////                'dirname' => "",
//                'extension' => "jpg",
//                'file_name' => '1515',
//                'height' => 55,
//                'host' => '',
//                'name' => '',
//                'size' => 53,
//                'sort' => 255,
//                'width' => 34,
//                'path' =>  $item['short_path'],
//                'url' =>  $item['path']
//            ];
//        }
//        $resData = [
//            'code' => 0,
//            'count' => 1,
//            'message' => '上传成功',
//            'data' => $data
//        ];
//        echo json_encode($resData);
//        exit();
////        $this->response($resData, 200, '上传成功');
//    }

    /**
     * 上传商家后台 编辑器图片
     */
    public function uploadEditorImage()
    {

        $savePath = !empty($this->request->param('save_path')) ? $this->request->param('save_path') : 'picture';
        $setting = [
            'driver' => sysconf('storage_type'),
            'root_path' => './static/upload/'.$savePath.'/' // 图片保存路径 默认为'./static/upload/picture/'
        ];


        if (!$this->request->isPost()) {
            $this->wrong(0, '未选择文件');
        }

        if ($this->request->isPost()) {
            // 创建目录
            if(!is_dir($setting['root_path'])) {
                @mkdir($setting['root_path'], 0777);
            }

            $file = request()->file();
            $uploadData = '';
            foreach ($file as $item) {
                foreach ($item as $value) {
                    $uploadData[] = $this->_uploadAndSaveFileData($setting, $value);

                }
            }


//            if(count($file) > 1) {
//                // 多图上传
//                $fileData = [];
//                foreach ($file as $item) {
//                    $fileData[] = $this->_uploadAndSaveFileData($setting, $item);
//                }
//                return $fileData;
//            }else {
//                // 单图上传
//                return $this->_uploadAndSaveFileData($setting, $file);
//            }

            $data = [];
            foreach ($uploadData as $item) {
                $data[] = [
                    'add_time' => time(),
//                'dirname' => "",
                    'extension' => "jpg",
                    'file_name' => '1515',
                    'height' => 55,
//                    'host' => '',
//                    'name' => '',
                    'size' => 53,
                    'sort' => 255,
                    'width' => 34,
                    'path' =>  $item['short_path'],
                    'url' =>  $item['path']
                ];
            }
            $resData = [
                'code' => 0,
                'count' => 1,
                'message' => '上传成功',
                'data' => $data
            ];
            echo json_encode($resData);
            exit();
        }


    }


    /**
     * 图片上传成功保存到Picture表
     * @param $setting
     * @return array|mixed
     */
    private function uploadAndSaveData($setting)
    {

//        if (!$this->request->isPost()) {
////             单图上传
////            die('<form method=post enctype="multipart/form-data">
////                    图片（base64） :<input name="image"><br/>
////                    图片（file） :<input name="image" type="file"><br/>
////                    <input type=submit>
////                  </form>');
//
//            // 多图上传
//            die('<form method=post enctype="multipart/form-data">
//                    图片（base64） :<input name="base64[]"><br/>
//                    图片（base64） :<input name="base64[]"><br/>
//                    图片（file） :<input name="image[]" type="file"><br/>
//                    图片（file） :<input name="image[]" type="file"><br/>
//                    <input type=submit>
//                  </form>');
//        }
//
        if (!$this->request->isPost()) {
            $this->wrong(0, '未选择文件');
        }

        if ($this->request->isPost()) {
            // 创建目录
            if(!is_dir($setting['root_path'])) {
                @mkdir($setting['root_path'], 0777);
            }

            //todo base64上传方式（主要是为了处理微信不支持 input file）
//            $smeta = $this->request->post();
//            if(isset($smeta['base64'])){
////                if(implode('', $smeta['base64']) != '') {
//                if(is_array($smeta['base64']) && count($smeta['base64']) > 1) {
//                    // 多图上传
//                    $fileData = [];
//                    foreach ($smeta['base64'] as $item) {
//                        $fileData[] = $this->_uploadAndSaveBase64Data($setting, $item);
//                    }
//                    return $fileData;
//                }else {
//                    // 单图上传
//                    return $this->_uploadAndSaveBase64Data($setting, $smeta['base64']);
//                }
//            }


            // todo file文件流方式上传（input file）
//
//            if (!request()->file('image')) {
//                $file = request()->file('file');
//            }else {
//                $file = request()->file('image');
//            }

            $file = request()->file();
            $fileData = '';
            foreach ($file as $item) {
                $fileData = $this->_uploadAndSaveFileData($setting, $item);
            }
            return $fileData;

//            if(count($file) > 1) {
//                // 多图上传
//                $fileData = [];
//                foreach ($file as $item) {
//                    $fileData[] = $this->_uploadAndSaveFileData($setting, $item);
//                }
//                return $fileData;
//            }else {
//                // 单图上传
//                return $this->_uploadAndSaveFileData($setting, $file);
//            }
        }
    }

    /**
     * 上传并保存file 图片
     * @param $setting
     * @param $file
     * @return mixed
     */
    private function _uploadAndSaveFileData($setting, $file) {
//        $pictureModel = new PictureModel();

        $validate = [
            'size'=>sysconf('upload_image_size'),
            'ext' => sysconf('upload_image_ext'),
        ];

        $info = $file->validate([$validate])->move($setting['root_path']);

        if($info){
            // 成功上传后 获取上传信息
            $savePath = substr($setting['root_path'], 1).date('Ymd').'/';
            $saveName = $info->getFilename();
            $shortPath = $savePath.$saveName;

            $data['short_path'] = $shortPath;
            $data['path'] = get_url_with_domain($shortPath);
            return $data; //文件上传成功
        }else{
            // 上传失败获取错误信息
            $this->wrong(0, $file->getError());
        }
    }

    /**
     * andy-发送邮件
     * @desc PHPMail
     * @parameter string to_email 接受者邮箱地址（必须）
     * @parameter string subject 邮件主题（必须）
     * @parameter string content 邮件内容（必须）
     * @parameter string to_name 接受者名称（可选）
     * @method POST
     */
    public function email()
    {
        $toemail = $this->param['to_email'];
        $toName = $this->param['to_name'];
        $subject = $this->param['subject'];
        $content = $this->param['content'];
        $result = send_mail($toemail, $toName, $subject, $content);
        if($result) {
            $this->response(null, 200, '邮件发送成功');
        }else {
            $this->response(null, 0, $result);
        }
    }

}
